package distributedbank.requests;

import java.io.IOException;
import java.util.List;
import java.util.Map.Entry;

import distributedbank.Wrapper;
import distributedbank.server.BankBranch;
import distributedbank.snapshot.RequestInfo;
import distributedbank.snapshot.Snapshots;

/**
 * Represents a request to deposit a certain amount of money to the given
 * account. This type of request is only sent as part of a TransferRequest.
 */
public class TransferDepositRequest extends Request
{
    private static final long serialVersionUID = 3795483718366112416L;

    private int amount; // amount to transfer in cents

    private RequestInfo ri;

    private int srcBranchId;

    /**
     * Note: the transactionId must be globally unique!
     */
    public TransferDepositRequest( int originatingBranchId, int branchId,
            int originatingAccountId, int accountId, int transactionId,
            int amount ) {
        super( branchId, accountId, transactionId );
        this.amount = amount;
        srcBranchId = originatingBranchId;
        ri = new RequestInfo( amount, originatingBranchId, branchId,
                originatingAccountId, accountId );
    }
    /**
     * Run a transfer request from remote bank branch.</br>
     * </br>
     * If this branch is listening to any channels' messages,</br>
     * and the srcChannel is not blocked</br>
     * record the message.
     */
    public void runRequest( BankBranch bankBranch, Wrapper wrapper )
            throws IOException {
        System.out.println( "Transfering to account " + this.accountId
                + " at branch " + this.branchId );
        bankBranch.getAccount( this.accountId ).deposit( this.amount,
                this.transactionId );
        Snapshots snapshots = bankBranch.getSnapshots();
        for( Entry<Integer, List<Request>> pair : snapshots.getChannels().entrySet() ) {
        	List<Integer> blockedChannels = snapshots.getBlockedChannels().get( pair.getKey());
        	if( blockedChannels == null ||
        			!blockedChannels.contains( srcBranchId )){
        		pair.getValue().add( this );
        	}
        }
    }
    /**
     * Get detailed information about the TransferRequest.
     * @return
     * 		RequestInfo for the TransferRequest.
     */
    public RequestInfo getRequestInfo() {
        return ri;
    }
}